package kino.command;

import kino.client.KinoClient;
import kino.common.KinoConstant;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

@KinoCommandEnable
public class ClientCommand extends AbstractKinoCommand{
    @Override
    public String doExecute(KinoClient client, String... argv) {
        Map<String, Object> extParam = client.getExtParam();
        if (extParam == null || extParam.size() == 0) {
            return KinoConstant.syntaxerr;
        }
        String method = (String)extParam.get("method");
        if (method == null) {
            return KinoConstant.syntaxerr;
        }
        if (method.equals("SETNAME")) {
            if (!extParam.containsKey("methodParam")) {
                return KinoConstant.syntaxerr;
            }
            client.setName((String)extParam.get("methodParam"));
        } else if (method.equals("GETNAME")){
            if (client.getName() == null) {
                return commandEncoder.encode("no name");
            }
            return commandEncoder.encode(client.getName());
        }
        return KinoConstant.ok;
    }

    @Override
    public Integer getArgc() {
        return 0;
    }

    @Override
    public String getCommandName() {
        return "client";
    }

    @Override
    public boolean aofFlag() {
        return false;
    }

    @Override
    public boolean hasExtParam() {
        return true;
    }

    @Override
    protected ExtParamParseResult doExtParamParse(String... argv) {
        ExtParamParseResult paramParseResult = new ExtParamParseResult();
        Map<String, Object> extParam = new HashMap<>();
        paramParseResult.setSuccess(true);
        paramParseResult.setExtParam(extParam);
        String param = argv[0];
        String upParam = param.toUpperCase(Locale.ROOT);
        // TODO 还未实现所有扩展参数
        if (upParam.equals("SETNAME")) {
            // 该参数后面应该再跟一个名字，后面不够提示错误
            if (argv.length != 2 ) {
                paramParseResult.setSuccess(false);
                paramParseResult.setErrorMsg(KinoConstant.syntaxerr);
                return paramParseResult;
            }
            String nextParam = argv[1];
            extParam.put("method", upParam);
            extParam.put("methodParam", nextParam);
        } else if (upParam.equals("GETNAME")) {
            if (argv.length != 1) {
                paramParseResult.setSuccess(false);
                paramParseResult.setErrorMsg(KinoConstant.syntaxerr);
                return paramParseResult;
            }
            extParam.put("method", upParam);
        } else {
            paramParseResult.setSuccess(false);
            paramParseResult.setErrorMsg(KinoConstant.syntaxerr);
            return paramParseResult;
        }
        return paramParseResult;
    }
}
